<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑驿站配置' : '新增驿站配置'"
    width="600px"
    :before-close="handleClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="stage-form"
    >
      <el-form-item label="驿站名称" prop="stageName">
        <el-input
          v-model="form.stageName"
          placeholder="请输入驿站名称"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="驿站地址" prop="stageAddress">
        <el-input
          v-model="form.stageAddress"
          type="textarea"
          :rows="3"
          placeholder="请输入驿站详细地址"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
          clearable
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
        >
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createExpressStage, updateExpressStage } from '@/api/express'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  stageData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  stageName: '',
  stageAddress: '',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  stageName: [
    { required: true, message: '请输入驿站名称', trigger: 'blur' },
    { min: 2, max: 50, message: '驿站名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  stageAddress: [
    { required: true, message: '请输入驿站地址', trigger: 'blur' },
    { min: 5, max: 200, message: '驿站地址长度在 5 到 200 个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 500, message: '备注不能超过500个字符', trigger: 'blur' }
  ]
})

// 监听visible变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal && props.isEdit && props.stageData) {
    // 编辑模式，填充数据
    nextTick(() => {
      Object.assign(form, {
        stageName: props.stageData.stageName || '',
        stageAddress: props.stageData.stageAddress || '',
        remark: props.stageData.remark || ''
      })
    })
  } else if (newVal && !props.isEdit) {
    // 新增模式，重置表单
    resetForm()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    stageName: '',
    stageAddress: '',
    remark: ''
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    if (props.isEdit) {
      // 编辑驿站配置
      const submitData = {
        param: {
          id: props.stageData.id,
          stageName: form.stageName,
          stageAddress: form.stageAddress,
          remark: form.remark || ''
        }
      }

      await updateExpressStage(submitData)
      ElMessage.success('驿站配置更新成功')
      
      // 关闭对话框并通知父组件刷新列表
      handleClose()
      emit('success')
    } else {
      // 新增驿站配置
      const submitData = {
        param: {
          stageName: form.stageName,
          stageAddress: form.stageAddress,
          remark: form.remark || ''
        }
      }

      await createExpressStage(submitData)
      ElMessage.success('驿站配置创建成功')
      
      // 关闭对话框并通知父组件刷新列表
      handleClose()
      emit('success')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.stage-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-textarea {
  resize: vertical;
}

/* 表单项标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

/* 输入框样式优化 */
:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: box-shadow 0.2s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset;
}

/* 文本域样式 */
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: box-shadow 0.2s ease;
  min-height: 80px;
}

:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-textarea.is-focus .el-textarea__inner) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style>
